package com.rentong.wx.cust.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.rentong.wx.cust.dao.CustUserServiceDao;
import com.rentong.wx.cust.dao.CustUserServiceTimeDao;
import com.rentong.wx.cust.dao.WxCustUserMapper;
import com.rentong.wx.cust.domain.CustServiceOrderTimeEntity;
import com.rentong.wx.cust.domain.CustUserServiceTimeEntity;
import com.rentong.wx.cust.domain.WxCustUser;
import com.rentong.wx.cust.dto.CustServiceOrderTimeVo;
import com.rentong.wx.cust.dto.CustUserServiceEntityDto;
import com.rentong.wx.cust.dto.CustUserServiceTimeEntityDto;
import com.rentong.wx.cust.dto.ServiceTimeDto;
import com.rentong.wx.cust.service.CustUserServiceTimeService;
import com.rentong.wx.cust.service.WxCustUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CustUserServiceTimeServiceImpl implements CustUserServiceTimeService {

    @Resource
    private CustUserServiceTimeDao custUserServiceTimeDao;

    @Autowired
    private CustUserServiceDao custUserServiceDao;

    @Autowired
    private WxCustUserMapper wxCustUserMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<CustUserServiceTimeEntityDto> getChefServiceTime(Long custId) {
        List<CustUserServiceTimeEntityDto> list = custUserServiceTimeDao.getChefServiceTimeList(custId);

        //把时间处理下，
        for (int i = 0; i < list.size(); i++) {
            CustUserServiceTimeEntityDto cus = list.get(i);

            //全天可约
            if (cus.getMorningFabu() == 1 && cus.getAfternoonFabu() == 1 && cus.getNightFabu() == 1) {
                list.get(i).setServiceTimeState(4);
            }

            //上午可约
            if (cus.getMorningFabu() == 1 && (cus.getAfternoonFabu() != 1 || cus.getNightFabu() != 1)) {
                list.get(i).setServiceTimeState(1);
            }

            //下午可约
            if (cus.getAfternoonFabu() == 1 && (cus.getMorningFabu() != 1 || cus.getNightFabu() != 1)) {
                list.get(i).setServiceTimeState(2);
            }

            //夜宵可约
            if (cus.getNightFabu() == 1 && (cus.getMorningFabu() != 1 || cus.getAfternoonFabu() != 1)) {
                list.get(i).setServiceTimeState(3);
            }

            //已预约
            if ((cus.getMorningFabu() == 3 || cus.getAfternoonFabu() == 3 || cus.getNightFabu() == 3)
                    && cus.getMorningFabu() != 1 && cus.getAfternoonFabu() != 1 && cus.getNightFabu() != 1) {
                list.get(i).setServiceTimeState(5);
            }

        }

        return list;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<CustServiceOrderTimeVo> getServiceTime(Long custId) {
        //所有已被预约的时间
        List<CustServiceOrderTimeEntity> custServiceOrderTimeEntities = custUserServiceTimeDao.getServiceTimeList(custId);
        return processServiceOrderTime(custServiceOrderTimeEntities);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveServiceTime(Long custId, List<ServiceTimeDto> serviceTimeDtoList) {
        List<CustUserServiceTimeEntity> custUserServiceTimeEntities = new ArrayList<>();

        for (ServiceTimeDto serviceTimeDto : serviceTimeDtoList) {
            CustUserServiceTimeEntity custUserServiceTimeEntity = new CustUserServiceTimeEntity();
            custUserServiceTimeEntity.setCustId(custId);
            custUserServiceTimeEntity.setServiceDate(serviceTimeDto.getServiceTime());
            List<Integer> fabus = serviceTimeDto.getFabus();
            // 初始化为默认值 2（未发布）
            int morningFabu = 2;
            int afternoonFabu = 2;
            int nightFabu = 2;

            if (fabus.contains(4)) {
                // 如果包含全天 (4)，所有时段都设置为 1
                morningFabu = 1;
                afternoonFabu = 1;
                nightFabu = 1;

                custUserServiceTimeEntity.setServiceTimeTwo(serviceTimeDto.getServiceTimeTwo());
            } else {
                // 判断具体时段
                if (fabus.contains(1)) {
                    morningFabu = 1;
                }
                if (fabus.contains(2)) {
                    afternoonFabu = 1;
                }
                if (fabus.contains(3)) {
                    nightFabu = 1;
                }
            }
            custUserServiceTimeEntity.setMorningFabu(morningFabu);
            custUserServiceTimeEntity.setAfternoonFabu(afternoonFabu);
            custUserServiceTimeEntity.setNightFabu(nightFabu);
            custUserServiceTimeEntity.setServiceTimeOne(serviceTimeDto.getServiceTimeOne());


            //设置周几
            int zhouji = calculateZhouji(serviceTimeDto.getServiceTime());
            custUserServiceTimeEntity.setZhouji(zhouji);
            custUserServiceTimeEntity.setAddTime(new Date());
            custUserServiceTimeEntity.setUpdateTime(new Date());
            custUserServiceTimeEntities.add(custUserServiceTimeEntity);
        }
        //如果服务介绍已经插入过，并且首次插入服务时间，则设置为师傅
        List<CustUserServiceEntityDto> serviceByCustId = custUserServiceDao.getServiceByCustId(custId);
        if (CollectionUtil.isNotEmpty(serviceByCustId)) {
            CustUserServiceTimeEntity custUserServiceTimeEntity = custUserServiceTimeDao.getbyCustId(custId);
            if (ObjectUtil.isEmpty(custUserServiceTimeEntity)) {
                WxCustUser wxCustUser = new WxCustUser();
                wxCustUser.setCustId(custId);
                wxCustUser.setGrade(2);
                wxCustUserMapper.updateByPrimaryKeySelective(wxCustUser);
            }
        }
        List<Date> dateList = custUserServiceTimeEntities.stream().map(CustUserServiceTimeEntity::getServiceDate).collect(Collectors.toList());
        custUserServiceTimeDao.deleteByServiceDates(dateList, custId);
        custUserServiceTimeDao.batchSave(custUserServiceTimeEntities);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<CustUserServiceTimeEntity> getServiceTimeList(Long custId) {
        return custUserServiceTimeDao.getCustServiceTimeList(custId);
    }

    @Override
    public void deleteServiceTime(List<Long> ids) {
        if (CollectionUtil.isNotEmpty(ids)) {
            for (Long id : ids) {
                custUserServiceTimeDao.deleteByPrimaryKey(id);
            }
        }
    }

    public List<CustServiceOrderTimeVo> processServiceOrderTime(List<CustServiceOrderTimeEntity> custServiceOrderTimeEntities) {
        List<CustServiceOrderTimeVo> result = new ArrayList<>();

        // 当前时间
        LocalDate today = LocalDate.now();
        LocalDate endDate = today.plusDays(30);

        // 遍历未来30天
        for (LocalDate date = today; !date.isAfter(endDate); date = date.plusDays(1)) {
            boolean dateMatched = false;

            // 检查当天是否有匹配的订单
            for (CustServiceOrderTimeEntity entity : custServiceOrderTimeEntities) {
                if (entity.getServiceOrderDate() != null) {
                    LocalDate serviceDate = entity.getServiceOrderDate()
                            .toInstant()
                            .atZone(ZoneId.systemDefault())
                            .toLocalDate();
                    if (serviceDate.equals(date)) {
                        // 日期匹配
                        dateMatched = true;
                        CustServiceOrderTimeVo vo = new CustServiceOrderTimeVo();
                        vo.setServiceOrderDate(serviceDate.atStartOfDay());

                        List<Integer> serviceOrderTypes = new ArrayList<>();
                        switch (entity.getServiceOrderType()) {
                            case 1:
                                serviceOrderTypes.add(2);
                                serviceOrderTypes.add(3);
                                break;
                            case 2:
                                serviceOrderTypes.add(1);
                                serviceOrderTypes.add(3);
                                break;
                            case 3:
                                serviceOrderTypes.add(1);
                                serviceOrderTypes.add(2);
                                break;
                            case 4:
                                serviceOrderTypes.add(0);
                                break;
                            default:
                                break;
                        }
                        vo.setServiceOrderType(serviceOrderTypes);
                        result.add(vo);
                        break;
                    }
                }
            }

            // 如果当天没有匹配的订单，创建一个默认项
            if (!dateMatched) {
                CustServiceOrderTimeVo vo = new CustServiceOrderTimeVo();
                vo.setServiceOrderDate(date.atStartOfDay());
                vo.setServiceOrderType(Collections.singletonList(4));
                result.add(vo);
            }
        }
        return result;
    }

    // 根据 Date 计算周几
    private int calculateZhouji(Date date) {
        // 转换为 LocalDate
        LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        // 获取 DayOfWeek
        DayOfWeek dayOfWeek = localDate.getDayOfWeek();
        // 将 DayOfWeek 转换为 1-7 表示的周一到周日
        return dayOfWeek.getValue(); // 周一=1，周日=7
    }

}